package com.bovink.camera;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;

import java.io.File;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity implements TextureView.SurfaceTextureListener {
    @BindView(R.id.iv_picture)
    ImageView pictureView;
    @BindView(R.id.tv_video)
    TextureView videoTextureView;
    @BindView(R.id.fl_content)
    FrameLayout contentFrameLayout;

    private MediaPlayer mediaPlayer;
    /**
     * 进入摄像头界面
     */
    private final static int CAMERA = 1001;
    private String videoPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        contentFrameLayout.removeView(videoTextureView);
        videoTextureView.setSurfaceTextureListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (videoPath != null) {
            System.out.println("MainActivity.onPause");
            contentFrameLayout.removeView(videoTextureView);
            videoTextureView.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (videoPath != null) {
            System.out.println("MainActivity.onResume");
            contentFrameLayout.addView(videoTextureView);
            videoTextureView.setVisibility(View.VISIBLE);

        }
    }

    @OnClick(R.id.btn_camera)
    void openCamera() {
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/supervisor");
        if (!file.exists()) {
            file.mkdirs();
        }
        CameraActivity.filePath = file.getAbsolutePath();
//        CameraActivity.type = CameraActivity.RECORD_VIDEO;
        Intent intent = new Intent(this, CameraActivity.class);
        startActivityForResult(intent, CAMERA);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        System.out.println("MainActivity.onActivityResult");
        if (requestCode == CAMERA) {
            if (resultCode == RESULT_OK) {
                int type = data.getIntExtra("type", 0);
                String path = data.getStringExtra("path");
                if (type == CameraActivity.TAKE_PICTURE) {

                    System.out.println("img = " + path);
                    Bitmap bitmap = CameraActivity.getBitmap(path);
                    videoPath = null;

                    pictureView.setVisibility(View.VISIBLE);
                    videoTextureView.setVisibility(View.GONE);

                    pictureView.setImageBitmap(bitmap);

                } else if (type == CameraActivity.RECORD_VIDEO) {

                    System.out.println("video = " + path);
                    videoPath = path;
                    pictureView.setVisibility(View.GONE);
                    videoTextureView.setVisibility(View.VISIBLE);
                }
            }

        } else {

            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void initPlayer(Surface surface) {
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(videoPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mediaPlayer.setSurface(surface);
        try {
            mediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
            @Override
            public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {

                if (width > height) {

                    videoTextureView.setRotation(90);
                    float scaleX = (float) width / videoTextureView.getWidth();
                    float scaleY = (float) height / videoTextureView.getHeight();
                    videoTextureView.setScaleX(scaleX);
                    videoTextureView.setScaleY(scaleY);
                }
            }
        });
        mediaPlayer.setLooping(true);
        mediaPlayer.start();
    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
        initPlayer(new Surface(surface));
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
        releasePlayer();
        System.out.println("MainActivity.onSurfaceTextureDestroyed");
        return true;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {


    }

    /**
     * 释放Player
     */
    private void releasePlayer() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}
